//
//  DispatchQueue+Extension.swift
//  FrameProduct
//
//  Created by delegate on 2024/2/3.
//

import Foundation
extension DispatchQueue {
    /// GCD实现定时器
    ///
    /// - Parameters:
    ///   - timeInterval: 间隔时间
    ///   - handler: 事件
    ///   - needRepeat: 是否重复
    @discardableResult
    public func interval(_ timeInterval: Double, needRepeat: Bool = false, handler: @escaping (DispatchSourceTimer?) -> Void) -> DispatchSourceTimer {
        
        let timer = DispatchSource.makeTimerSource(flags: [], queue: self)
        timer.schedule(deadline: .now(), repeating: timeInterval)
        timer.setEventHandler {
            self.async {
                if needRepeat {
                    handler(timer)
                } else {
                    timer.cancel()
                    handler(nil)
                }
            }
        }
        timer.resume()
        return timer
    }
}
